import type { ImUser, User, UserWrapper } from '@/api/types/userWrapper'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  findUserOrigin,
} from '@/api/authService'
import { useUnifiedTokenStore } from './useUnifiedToken'

export const emptyUser: User = {
  id: undefined,
  userName: '',
  nickName: '',
  sex: undefined,
  type: undefined,
  signature: '',
  headImage: '',
  headImageThumb: '',
  online: false,
  isBanned: false,
  reason: '',
  userNo: '',
  ip: '',
  username: '',
  password: '',
  nickname: '',
  avatarUrl: '',
  mobile: '',
  email: '',
  address: '',
  vipNew: undefined,
  introduce: '',
  country: '',
  province: '',
  city: '',
  wxBind: '',
  usernameFlag: '',
  ankiHostKey: '',
  vipType: undefined,
  vipName: '',
  vipExpireTime: '',
  inviteCode: '',
  createTime: '',
  updateTime: '',
  isDelete: 0,
  isAscribe: 0,
  idfa: '',
  uuid: '',
  oaid: '',
  imei: '',
  userIdentifier: '',
  givenName: '',
  familyName: '',
  authorizationCode: '',
  identityToken: '',
  platform: '',
  token: '',
  userAgent: '',
  scanTimes: 0,
  deviceName: '',
  deviceType: '',
  drawCount: 0,
  toolCount: 0,
  chatCount: 0,
  dubCount: 0,
  dubNumber: 0,
  freeCount: 0,
  channelName: '',
  register: false,
  lawyerAuthInfo: undefined,
}

export const emptyImUser: ImUser = {
  refreshTokenExpiresIn: undefined,
  accessTokenExpiresIn: undefined,
  accessToken: '',
  refreshToken: '',
}

export const emptyUserWrapper: UserWrapper = {
  legalUser: { ...emptyUser },
  imUser: { ...emptyImUser },
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 定义用户信息
    const userInfo = ref<UserWrapper>({ ...emptyUserWrapper })
    // 设置用户信息
    const setUserInfo = (val: UserWrapper) => {
      console.log('设置用户信息', val)
      // 若头像为空 则使用默认头像
      useUnifiedTokenStore().onLoginSuccess(val)

      userInfo.value = val
    }
    const setUserAvatar = (headImage?: string, headerImageThumb?: string) => {
      userInfo.value.legalUser.headImage = headImage
      userInfo.value.legalUser.headImageThumb = headerImageThumb
      console.log('设置用户头像', headImage)
      console.log('userInfo', userInfo.value)
    }
    // 删除用户信息
    const clearUserInfo = () => {
      userInfo.value = { ...emptyUserWrapper }
      useUnifiedTokenStore().logout()
      uni.removeStorageSync('user')
    }

    /**
     * 获取用户信息
     */
    const fetchUserInfo = async () => {
      const res = await findUserOrigin()
      setUserInfo(res)
      return res
    }

    return {
      userInfo,
      clearUserInfo,
      fetchUserInfo,
      setUserInfo,
      setUserAvatar,
    }
  },
  {
    persist: true,
  },
)
